package org.team4.dao.meta;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.team4.dao.GenericDAO;
import org.team4.domain.RoleModuleUsers;
import org.team4.domain.RoleUsers;
import org.team4.exception.CRUDException;
import org.team4.util.CacheUtil;
import org.team4.util.Validate;
import org.team4.vo.RoleCache;

import org.team4.dao.meta.RoleModuleUsersDAO;


public class RoleModuleUsersDAO extends GenericDAO<RoleModuleUsers> {

	private static final long serialVersionUID = 3406989631364286984L;
	private static RoleModuleUsersDAO instance;
	
	public static RoleModuleUsersDAO getInstance(SessionFactory sessionFactory) {
        if(instance == null) {
            instance =  new RoleModuleUsersDAO(sessionFactory);
        }
        return instance;
    }
	
    /**
     * 构造函数
     * 
     * @param sessionFactory
     */
    private RoleModuleUsersDAO(SessionFactory sessionFactory) {
        super(sessionFactory, RoleModuleUsers.class);
    }
    
    /**
     * session用到的角色模块用户集合
     * 
     * @param ruList
     * @return
     * @throws CRUDException
     */
    public HashMap<String, String> findRoleModuleUsers(List<RoleUsers> ruList, String userId) throws CRUDException {
    	//从缓存中取出现有权限
        HashMap<String, String> moduleUsers = new HashMap<String, String>();
        RoleCache roleCache = (RoleCache) CacheUtil.get(RoleCache.CACHE_NAME, userId);
        if(roleCache != null) {
        	moduleUsers = roleCache.getModuleUsers();
        }
        if (Validate.collectionNotNull(ruList)) {
            for (RoleUsers ru : ruList) {
                for (Iterator iter = ru.getRole().getRoleModuleUsers().iterator(); iter.hasNext();) {
                    RoleModuleUsers rmu = (RoleModuleUsers) iter.next();
                    String sessionUsers = moduleUsers.get(rmu.getModule().getId());
                    StringBuffer userIds = new StringBuffer();
                    if (Validate.notNull(sessionUsers))
                        userIds.append(sessionUsers);
                    String[] nextUsersIds = rmu.getUsers().split(",");
                    for (int i = 0; i < nextUsersIds.length; i++) {
                        if (Validate.notNull(nextUsersIds[i])) {
                            if (userIds.indexOf(nextUsersIds[i]) < 0)
                                userIds.append(nextUsersIds[i] + ",");
                        }
                    }
                    moduleUsers.put(rmu.getModule().getId(), userIds.toString());
                }
            }
        }
        return moduleUsers;
    }

}
